package com.tour.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tour.common.Const;
import com.tour.common.ResponseCode;
import com.tour.common.ServerResponse;
import com.tour.common.TokenCache;
import com.tour.dao.UserMapper;
import com.tour.pojo.EasyUIDataGridResult;
import com.tour.pojo.User;
import com.tour.service.IUserService;
import com.tour.util.MD5Util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Properties;
import java.util.UUID;


/**
 * Created by geely
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    //测试临时使用的
    public static String tempCode = null;

    /**
     * 用户登录
     */
    @Override
    public ServerResponse<User> login(String username, String password) {
        int resultCount = userMapper.checkUsername(username);
        if(resultCount == 0 ){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }

        String md5Password = MD5Util.MD5EncodeUtf8(password);
        System.out.println("===================================="+md5Password);
        User user  = userMapper.selectLogin(username,md5Password);
        if(user == null){
            return ServerResponse.createByErrorMessage("密码错误");
        }

        user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功",user);
    }


    //用户注册
    public ServerResponse<String> register(User user,String validCode){

        if(validCode==null){
        	return ServerResponse.createByErrorMessage("请输入验证码");
        }
        
        ServerResponse validResponse = this.checkValid(user.getUsername(),Const.USERNAME);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        
        //验证邮箱是否存在
        validResponse = this.checkValid(user.getEmail(),Const.EMAIL);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        
        //验证短信是否正确
        validResponse = this.checkMes(validCode);
        if(!validResponse.isSuccess()){
        	return validResponse;
        }
        
        user.setRole(Const.Role.ROLE_CUSTOMER);
        //MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount = userMapper.insert(user);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    //发送验证码
	@Override
	public String sendCheckMes(String phone) {
	 	String Url = Const.checkUrl;
    	HttpClient client = new HttpClient(); 
		PostMethod method = new PostMethod(Url);

		client.getParams().setContentCharset("UTF-8");
		method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

		int mobile_code = (int)((Math.random()*9+1)*100000);
		
	    String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");

	    NameValuePair[] data = {//提交短信
			    new NameValuePair("account", "C86076862"), //查看用户名是登录用户中心->验证码短信->产品总览->APIID
			    new NameValuePair("password", "594a365fb76173bd05e7773e760b1c79"),  //查看密码请登录用户中心->验证码短信->产品总览->APIKEY		
			    new NameValuePair("mobile", phone), 
			    new NameValuePair("content", content),
			    new NameValuePair("time", System.currentTimeMillis()+60000+""), 
			    new NameValuePair("format", "json")
		};
		method.setRequestBody(data);
		try {
			client.executeMethod(method);
//		String SubmitResult =method.getResponseBodyAsString();
//		//打印
//		System.out.println(SubmitResult);
//
//		Document doc = DocumentHelper.parseText(SubmitResult);
//		Element root = doc.getRootElement();
		tempCode = mobile_code+"";
		System.out.println(tempCode);
		return tempCode;
		}catch (Exception e) {
			e.printStackTrace();
			return tempCode;
		}
    }
		
	


     //验证信息是否正确
	@Override
	public ServerResponse<String> checkMes(String validCode) {
		if(tempCode.equals(validCode)){
			return ServerResponse.createBySuccessMessage("验证码正确");
		}
		
		return ServerResponse.createByErrorMessage("验证码不正确，请重新输入");
	}

	


    public ServerResponse<String> checkValid(String str,String type){
        if(org.apache.commons.lang3.StringUtils.isNotBlank(type)){
            //开始校验
            if(Const.USERNAME.equals(type)){
                int resultCount = userMapper.checkUsername(str);
                if(resultCount > 0 ){
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }
            if(Const.EMAIL.equals(type)){
                int resultCount = userMapper.checkEmail(str);
                if(resultCount > 0 ){
                    return ServerResponse.createByErrorMessage("email已存在");
                }
            }
        }else{
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    public ServerResponse selectQuestion(String username){

        ServerResponse validResponse = this.checkValid(username,Const.USERNAME);
        if(validResponse.isSuccess()){
            //用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if(org.apache.commons.lang3.StringUtils.isNotBlank(question)){
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("找回密码的问题是空的");
    }

    public ServerResponse<String> checkAnswer(String username,String question,String answer){
        int resultCount = userMapper.checkAnswer(username,question,answer);
        if(resultCount>0){
            //说明问题及问题答案是这个用户的,并且是正确的
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题的答案错误");
    }



    /*public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){
        if(org.apache.commons.lang3.StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMessage("参数错误,token需要传递");
        }
        ServerResponse validResponse = this.checkValid(username,Const.USERNAME);
        if(validResponse.isSuccess()){
            //用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if(org.apache.commons.lang3.StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token无效或者过期");
        }

        if(org.apache.commons.lang3.StringUtils.equals(forgetToken,token)){
            String md5Password  = MD5Util.MD5EncodeUtf8(passwordNew);
            int rowCount = userMapper.updatePasswordByUsername(username,md5Password);

            if(rowCount > 0){
                return ServerResponse.createBySuccessMessage("修改密码成功"); 
            }
        }else{
            return ServerResponse.createByErrorMessage("token错误,请重新获取重置密码的token");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }*/
    
    //验证手机号码是否存在
    public ServerResponse<String> checkPhone(String phone) {
		int resultcount=userMapper.checkPhone(phone);
		if(resultcount>0){
			return ServerResponse.createBySuccessMessage("手机号码存在");
		}
		return ServerResponse.createByErrorMessage("手机号码不存在，请仔细检查手机号码");
	}
    
    //验证用户昵称
    @Override
	public ServerResponse<String> checkUsername(String username) {
		int resultcount = userMapper.checkUsername(username);
		if(resultcount > 0){
			return ServerResponse.createBySuccessMessage("用户昵称已存在");
		}
		return ServerResponse.createByErrorMessage("用户昵称不存在");
	}


	
    
    
    //忘记密码
     public ServerResponse<String> forgetResetPassword(String phone,String passwordNew,String validCode){
		
    	 ServerResponse validResponse=this.checkValid(phone, Const.USERNAME);
    	 if(!validResponse.isSuccess()){
    		return validResponse;
    	 }
    	 
    	 validResponse = this.checkMes(validCode);
    	 if(!validResponse.isSuccess()){
    		 return validResponse;
    	 }
    	 
    	 //设置新密码
    	 String md5Password=MD5Util.MD5EncodeUtf8(passwordNew);
    	 System.out.println("++++++++++++++++++++++newpassword"+passwordNew);
    	 System.out.println("++++++++++++++++++++++newpassword"+md5Password);
    	 int rowCount=userMapper.updatePasswordPhone(phone, md5Password);
    	 if(rowCount>0){
    		 return ServerResponse.createBySuccessMessage("密码修改成功");
    	 }
    	 return ServerResponse.createBySuccessMessage("密码修改失败");
    	
    }
    
    
    
   //验证旧密码是否正确
    
    public ServerResponse<String> checkPassword(String passwordOld,User user){
    //防止横向越权,要校验一下这个用户的旧密码,一定要指定是这个用户.因为我们会查询一个count(1),如果不指定id,那么结果就是true啦count>0;
    	System.out.println("old=++++++++++++++++++++++++"+passwordOld);
    	int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld),user.getUserId());
    	if(resultCount == 0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
    	System.out.println("old=++++++++++++++++++++++++"+MD5Util.MD5EncodeUtf8(passwordOld));
		return ServerResponse.createBySuccessMessage("旧密码正确");
    }
   
    
   //更新密码
    public ServerResponse<String> resetPassword(String passwordNew,User user){
        //防止横向越权,要校验一下这个用户的旧密码,一定要指定是这个用户.因为我们会查询一个count(1),如果不指定id,那么结果就是true啦count>0;
        System.out.println("=newmd5==========="+MD5Util.MD5EncodeUtf8(passwordNew));
          user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新失败");
    }


    public ServerResponse<User> updateInformation(User user){
        //username是不能被更新的
        //email也要进行一个校验,校验新的email是不是已经存在,并且存在的email如果相同的话,不能是我们当前的这个用户的.
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(),user.getUserId());
        if(resultCount > 0){
            return ServerResponse.createByErrorMessage("email已存在,请更换email再尝试更新");
        }
        User updateUser = new User();
        updateUser.setUserId(user.getUserId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updateCount > 0){
            return ServerResponse.createBySuccess("更新个人信息成功",updateUser);
        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
    }



    public ServerResponse<User> getInformation(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);

    }




    //backend

    /**
     * 校验是否是管理员
     * @param user
     * @return
     */
    public ServerResponse checkAdminRole(User user){
        if(user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }



 // 获取用户列表
 	public EasyUIDataGridResult getUserList(int pageNum, int pageSize) {
 		// startPage--start
 		// 填充自己的sql查询逻辑
 		// pageHelper-收尾
 		PageHelper.startPage(pageNum, pageSize);
 		List<User> userList = userMapper.selectList();
 		for (User user : userList) {
 			System.out.println(user);
 		}
 		PageInfo pageResult = new PageInfo(userList);
 		pageResult.setList(userList);
 		// 创建一个返回值对象
 		EasyUIDataGridResult result = new EasyUIDataGridResult();
 		result.setRows(userList);
 		// 取分页结果
 		PageInfo pageInfo = new PageInfo(userList);
 		// 取总记录数
 		long total = pageInfo.getTotal();
 		result.setTotal(total);
 		return result;
 	}
 	
 	public ServerResponse setStatus(Integer id, Boolean status){
 		 if(id == null || status == null){
 			 return
 			 ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
 			 }
 			 User user = new User();
 			 user.setUserId(id);
 			 user.setFreeze(status);
 			 int rowCount = userMapper.updateByPrimaryKeySelective(user);
 			 if(rowCount > 0){
 			 return ServerResponse.createBySuccess("修改用户状态成功");
 			 }
 			 return ServerResponse.createByErrorMessage("修改用户状态失败");
 	}
}
